<?php

	session_start();
	
	require_once '../db/db.php';
	
	$error = false;
	
	// delete selected team
	if(isset($_POST['delete_team']) && $_POST['delete_team'] == true) {
		
		// sanitize team id
		if(filter_var($_POST['id'], FILTER_VALIDATE_INT)) {
		
			$id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);
		
		}else{
		
			$message[] = '<p class="error">Cannot validate team.</p>';
			$error = true;
			
		}
		
		// use transaction to modify each player on team, delete each assoc.
		// roster and rosters_players equiveleanat
		try {
			
			$db->beginTransaction();
			
			// remove players from team
			$db->exec("UPDATE players SET team_id = 0 WHERE team_id = " . $id);
			
			// delete rosters and rosters_players entries
			$sql = "SELECT roster_id FROM rosters WHERE team_id = " . $id;
			foreach($db->query($sql) as $roster) {
				
				$db->exec("DELETE FROM rosters_players WHERE roster_id = " . $roster['roster_id']);
				$db->exec("DELETE FROM rosters WHERE roster_id = " . $roster['roster_id']);
				
			}
			
			// delete team
			$db->exec("DELETE FROM teams WHERE team_id = " . $id);
			
			$db->commit();
			
			$message[] = '<p class="notice">Successfully deleted your team.</p>';
			
		} catch(PDOException $e) {
			
			$db->rollBack();
			$message[] = '<p class="error">Could not delete team.</p>';
			$message[] = '<p class="notice">' . $e->getMessage() . '</p>';
			$error = true;	
			
		}
		
	}
	
	if(isset($message)) foreach($message as $m) print $m;

?>